<template>
  <div class="layout-product">
		<div class="brand-name">{{`品牌名称：${brandName}`}}</div>
		<div class="auto-content" v-loading="pageLoading">
			<el-collapse v-if="brandDetail.length" :value="collapsedItem">
					<el-collapse-item  v-for="(item, index) in brandDetail" :key="index" :name="index">
					<template slot="title">
						<div style="width: 95%;">
							<span>{{item.productName}}</span>
							<el-button style="margin-left: 24px;" type="danger" size="mini" @click.stop="handlerDel(index, item)">删除</el-button>
						</div>
					</template>
					<div class="product-info">
						<div>供应商：</div>
						<el-select v-model="item.partnerCode" size="medium" filterable clearable placeholder="请选择供应商" @change="() => statusChange(index)">
							<el-option
								v-for="item in authorOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value">
							</el-option>
						</el-select>
					</div>
					<div class="product-table">
						<el-table
							:ref="`table${index}`"
							:data="item.goodsList"
							style="width: 100%;"
							border
							:max-height="205"
							header-row-class-name="short-row"
							row-class-name="short-row"
							cell-class-name="short-cell"
							@selection-change="(selection) => {selectColumn(index, selection)}"
						>
							<!--<el-table-column width="100" align="center" label="操作">
								<template slot-scope="scope">
									<el-switch
										v-model="scope.row.checked"
										@change="() => {statusChange(index)}"
										active-color="#409eff"
										inactive-color="#dcdfe6">
									</el-switch>
								</template>
							</el-table-column>-->
							<el-table-column
								type="selection"
								align="center"
								width="60">
							</el-table-column>
							<el-table-column v-for="(column, cIndex) in item.column" :key="cIndex" :label="column">
								<template slot-scope="scope">
									{{scope.row.goodsSpec[cIndex].specValue}}
								</template>
							</el-table-column>
							<el-table-column label="备注" width="220">
								<template slot-scope="scope">
									<el-input size="medium" v-model="scope.row.remark" @change="() => {statusChange(index)}" placeholder="请输入备注"></el-input>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</el-collapse-item>
			</el-collapse>
			<div class="add-product">
				<el-button type="primary" size="small" @click="addProduct">新增产品</el-button>
			</div>
		</div>
		<div class="save-page">
			<el-button type="primary" @click="savePageData">保 存</el-button>
		</div>
		<el-dialog
      title="新增产品"
      :visible.sync="dialogVisible"
      width="500px">
      <el-form ref="productForm" :model="productItem" label-width="150px" size="small" :rules="productRules">
        <el-form-item label="产品名称：" prop="productCode">
          <el-select v-model="productItem.productCode" filterable placeholder="请选择产品">
			<el-option
				v-for="item in productOptions"
				:key="item.value"
				:disabled="item.disabled"
				:label="item.label"
				:value="item.value">
			</el-option>
		</el-select>
        </el-form-item>
				<el-form-item label="供应商名称：">
          <el-select v-model="productItem.partnerCode" filterable clearable placeholder="请选择供应商">
						<el-option
							v-for="item in authorOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="saveProduct" size="small">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getBrandGoodsDetail, getProductListByBrand, getSupplierList, getGoodsByProduct, saveBrandGoods} from "@/api/product";
import {brandDetails, productList, supplierList, productGoods} from './mock'
export default {
  data() {
    return {
			dialogVisible: false, // 新增产品dialog
			brandName: '', // 品牌名称
			brandDetail: [], // 当前品牌下的产品及商品详情
			productOptions: [], // 产品列表
			authorOptions: [], // 供应商列表
			productItem: {
				productCode: '',
				productName: '',
				partnerCode: '',
				partnerName: '',
				insert: false,
			},
			productRules: {
						productCode: [
							{ required: true, message: '请选择产品', trigger: 'change' },
						],
			},
			collapsedItem: [0],
			pageLoading: true,
    };
  },
  created() {
	  this.brandCode = this.$route.query.code
	  this.brandName = this.$route.query.name
	  this.getBrandDetails()
	  this.getProductList()
	  this.getSupplierList()
  },
  methods: {
	// 删除产品
	handlerDel (index) {
		let option = this.brandDetail.splice(index, 1)
		if (option.length) {
			if (!option[0].insert) {
				this.delProducts.push(option[0].productCode)
				const editIndex = this.editProducts.findIndex(item => item === option[0].productCode)
				if (editIndex > -1) {
					this.editProducts.splice(editIndex, 1)
				}
			} else {
				const addIndex = this.addProducts.findIndex(item => item === option[0].productCode)
				if (addIndex > -1) {
					this.addProducts.splice(addIndex, 1)
				}
			}
			this.setProductDisable()
		}
	},
	// 查询品牌下的所有商品信息
	getBrandDetails () {
		const code = this.$route.query.code
		this.addProducts = []
		this.delProducts = []
		this.editProducts = []
		getBrandGoodsDetail(code).then(res => {
			const resData = res.data || []
			this.brandDetail = []
			resData.forEach(item => {
				let {productCode, productName, partnerCode, partnerName, goodsList} = item
				let option = {productCode, productName, partnerCode, partnerName}
				option.column = goodsList[0].goodsSpec.map(good => good.specName)
				option.goodsList = JSON.parse(JSON.stringify(goodsList))
				this.brandDetail.push(option)
			})
		}).catch(() => {
			if (location.href.includes('localhost')) {
				const resData = brandDetails || []
				this.brandDetail = []
				resData.forEach(item => {
					let {productCode, productName, partnerCode, partnerName, goodsList} = item
					let option = {productCode, productName, partnerCode, partnerName}
					option.column = goodsList[0].goodsSpec.map(good => good.specName)
					option.goodsList = JSON.parse(JSON.stringify(goodsList))
					this.brandDetail.push(option)
				})
			}
		}).finally(() => {
			this.pageLoading = false
			// 设置默认勾选项
			this.$nextTick(() => {
				this.brandDetail.forEach((item, index) => {
					const $table = this.$refs[`table${index}`][0]
					$table.clearSelection()
					item.goodsList.forEach(good => {
						if (good.checked) {
							$table.toggleRowSelection(good, true)
						}
					})
				})
			})
			setTimeout(() => {
				this.selectable = true
			}, 500)
		})
	},
	// 编辑状态
	statusChange (index) {
		// 相当于编辑过产品
		let {insert, productCode} = this.brandDetail[index]
		if (insert === undefined) {
			if (!this.editProducts.includes(productCode)) {
				this.editProducts.push(productCode)
			}
		}
	},
	selectColumn (index, selection) {
		if (!this.selectable) {
			return
		}
		const ids = selection.map(item => item.id)
		this.brandDetail[index].goodsList.forEach(item => {
			item.checked = ids.includes(item.id)
		})
		this.statusChange(index)
	},
	// 请求品牌下产品列表
	getProductList () {
		const brandCode = this.$route.query.code
		getProductListByBrand(brandCode).then(res => {
			if (res.code === 200) {
				res.data.list.forEach(item => {
					let {productCode, productName} = item
					let option = {
						label: productName,
						value: productCode,
						disabled: false
					}
					this.productOptions.push(option)
				})
			}
		})
	},
	// 请求供应商列表
	getSupplierList() {
		getSupplierList(this.brandCode).then(res => {
			if (res.code === 200) {
				const resData = res.data.list || []
				resData.forEach(item => {
					let {partnerCode, partnerName} = item
					this.authorOptions.push({
						label: partnerName,
						value: partnerCode,
					})
				})
			}
		})
	},
	// 设置产品下拉列表选项
	setProductDisable () {
		this.productOptions.forEach(item => {
			item.disabled = Boolean(this.brandDetail.find(p => p.productCode == item.value))
		})
	},
	// 点击新增产品
	addProduct () {
		if (this.$refs.productForm) {
			this.$refs.productForm.resetFields()
		}
		this.setProductDisable()
		this.productItem = {
			productCode: '',
			productName: '',
			partnerCode: '',
			partnerName: '',
			insert: true,
		}
		this.dialogVisible = true
	},
	// 保存页面数据
	savePageData () {
		const params = {
			insert: [],
			update: [],
			delete: this.delProducts.concat()
		}
		this.brandDetail.forEach(item => {
			if (this.addProducts.includes(item.productCode)) {
				let option = JSON.parse(JSON.stringify(item))
				option.brandCode = this.brandCode
				delete option.column
				params.insert.push(option)
			}
			if (this.editProducts.includes(item.productCode)) {
				let option = JSON.parse(JSON.stringify(item))
				option.brandCode = this.brandCode
				delete option.column
				params.update.push(option)
			}
		})
		if (params.insert.length || params.update.length || params.delete.length) {
			saveBrandGoods(params).then(res => {
				if (res.code == 200) {
					this.$message.success('保存成功')
					this.getBrandDetails()
				} else {
					this.$message.error('保存失败')
				}
			}).catch(() => {
				this.$message.error('保存失败')
			})
		} else {
			this.$message.success('保存成功')
		}
	},
	// 新增产品--保存
    saveProduct () {
		this.$refs.productForm.validate(valid => {
			if (valid) {
				let {productCode, partnerCode, insert} = this.productItem
				const productName = this.productOptions.find(item => item.value === productCode).label
				let partnerName = ''
				if (partnerCode) {
					partnerName = this.authorOptions.find(item => item.value === partnerCode).label
				}
				if (!this.addProducts.includes(productCode)) {
					this.addProducts.push(productCode)
				}
				let option = {productCode, productName, partnerCode, partnerName}
				option.insert = true
				option.column = []
				option.goodsList = []
				getGoodsByProduct(productCode).then(res => {
					if (res.code === 200) {
						const resData = res.data || []
						if(resData.length==0){
								this.$message.error('该产品为配置规格商品')
								return
						}
						resData.forEach(item => {
							item.checked = false
						})
						option.column = resData[0].goodsSpec.map(good => good.specName)
						option.goodsList = JSON.parse(JSON.stringify(resData))
						this.brandDetail.push(option)
						this.dialogVisible = false
					}
				})
			}
		})
	}
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.layout-product {
	width: 100%;
	height: 100%;
	overflow-y: hidden;
	max-width: 1200px;
	margin: 0 auto;
  padding: 24px 0 12px;
	font-size: 14px;
	display: flex;
	flex-direction: column;
	.brand-name{
		margin-bottom: 24px;
		font-size: 16px;
	}
	.auto-content{
		flex: 1;
    overflow-y: auto;
	}
  .product-table {
    .el-input-number--small {
      width: 100%;
    }
  }
	.product-info{
		display: flex;
		align-items: center;
		margin: 12px 0;
	}
  
  .product-table /deep/ {
    th.el-table__cell {
      background-color: #f5f7fa;
    }
    .el-input-number {
      width: 100%;
    }
		.el-collapse-item__content{
			padding-bottom: 0;
		}
  }
	/deep/ .el-collapse-item__header{
		flex-direction: row-reverse;
		i{
			margin: 0 32px 0 auto;
		}
	}
  .add-product{
	  margin-top: 12px;
  }
  .save-page{
	  width: 100%;
	  text-align: center;
  }
  .el-select{
	  .el-input__inner{
		  height: 28px;
		  line-height: 28px;
	  }
  }
	/deep/ .short-row th{
		padding: 6px 0;
	}
	/deep/ .short-cell{
		padding: 2px 0;
	}

}
</style>